/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 快宝网络 v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import type {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import ProLayout from '@ant-design/pro-layout';
import React, { useEffect, useRef, useState } from 'react';
import type { Dispatch } from 'umi';
import { Redirect, Link, useIntl, connect, history, useSelector } from 'umi';
import { Spin } from 'antd';
import Authorized from '@/utils/Authorized';
import type { ConnectState } from '@/models/connect';
import Footer from './Footer';
import logo from '../assets/logo.svg';
import RightContent from '@/components/GlobalHeader/RightContent';
import PageTabs from '@/components/PageTabs';
import type { ChildrenMap } from '@/components/PageTabs';
import { useWindowSizeChange } from '@/utils/hooks';
import { fixPathnameHasParent } from '@/utils/hooks/pageTabs';
import { useUma } from '@/utils/hooks/uma';
import RedPoint from '@/components/_pages/red-point';

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: Record<string, MenuDataItem>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  vendor?: string;
  currentUser: any;
}

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    location: { pathname } = {
      pathname: '/',
    },
    route,
    currentUser: { isManager },
  } = props;

  const {
    loading: { effects: loadingEffects },
  } = useSelector((state: ConnectState) => state);
  const userGetting = loadingEffects['user/fetchCurrent'];

  // 监听视窗大小
  useWindowSizeChange();
  // 友盟统计
  useUma();

  const menuDataRef = useRef<MenuDataItem[]>([]);
  const childrenMapRef = useRef<ChildrenMap>({});

  const [childrenMap, setChildrenMap] = useState({});

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };

  /**
   * use Authorized check all menu item
   */

  const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] => {
    return menuList
      .filter((item: any) => isManager || item.authority !== 'admin')
      .map((item: any) => {
        const localItem = {
          authority: item.path.replace('/f/', ''),
          ...item,
          routes: item.routes ? menuDataRender(item.routes) : undefined,
        };
        return Authorized.check('', localItem, null) as MenuDataItem;
      });
  };

  const { formatMessage } = useIntl();

  useEffect(() => {
    if (!pathname) return;
    childrenMapRef.current[fixPathnameHasParent(pathname)] = children;
    setChildrenMap({ ...childrenMapRef.current });
  }, [pathname]);

  // 是否重定向路由
  const isRedirect = pathname && /^\/f?\/?$/.test(pathname);

  return (
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      {...props}
      {...settings}
      title={settings.title}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || !menuItemProps.path) {
          return defaultDom;
        }
        return (
          <Link to={menuItemProps.path}>
            <RedPoint pathname={menuItemProps.path}>{defaultDom}</RedPoint>
          </Link>
        );
      }}
      breadcrumbRender={() => []}
      footerRender={() => <Footer />}
      rightContentRender={({ menuData }) => <RightContent menuData={menuData} />}
      menuDataRender={menuDataRender}
      postMenuData={(menuData) => {
        menuDataRef.current = menuData || [];
        return menuData || [];
      }}
      disableContentMargin
    >
      <Spin spinning={userGetting}>
        <PageTabs route={route} childrenMap={childrenMap} />
      </Spin>
      {isRedirect && <Redirect to='/f/tools/quickLogin' />}
    </ProLayout>
  );
};

export default connect(({ global, settings, user }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  vendor: user.currentUser!.vendor,
  currentUser: user.currentUser,
  isManager: user.isManager,
}))(BasicLayout);
